package me.jayramafisher.mcsurvival;

import org.jnbt.*;
import java.io.File;

/**
*The GroupManager class stores all of the groups, their members, and their default permissions.
*/

public class GroupManager
{

    /**
    *A reference to the parent SurvivalPlugin to access the different output streams.
    */

    private SurvivalPlugin parent;

    /**
    *Stores the group data in an nbt structure
    */

    private Tag groups;

    /**
    *Creates a GroupManager that loads its data from "plugins/MCSurvival/groups.nbt". Only one GroupManager should exist at any time.
    */

    public GroupManager(SurvivalPlugin nparent)
    {
        parent = nparent;
        //load the NBT
        try {
            groups = NBTManager.load(new File("plugins/MCSurvival/groups.nbt"));
            if(validate()); //do nothing
            else throw new Exception();
        } catch(Exception e) {
            groups = null;
        }
        if(groups == null) parent.log.println("Error: Failed to load groups.nbt");
        else parent.log.println("groups.nbt loaded successfully");
    }

    public void onDisable()
    {
        //save the NBT
        try
        {
            NBTManager.save(new File("plugins/MCSurvival/groups.nbt"),groups);
        } catch(Exception e)
        {
            groups = null;
        }
        if(groups == null) parent.log.println("Error: Failed to save groups.nbt");
        else parent.log.println("groups.nbt saved successfully.");
    }

    /**
    *Checks to make sure the NBT object meets the specifications for the groups.nbt sub-format. (TODO)
    */

    public boolean validate()
    {
        try {
            //check root
            if(!(groups instanceof CompoundTag)) return false;
            //check for admin in root
            if(!(NBTManager.get(groups,"admin") instanceof StringTag)) return false;
            //check for managers in root
            if(!(NBTManager.get(groups,"managers") instanceof ListTag)) return false;
            //check for permissions in root
            if(!(NBTManager.get(groups,"permissions") instanceof ListTag)) return false;
        } catch(Exception e) { return false; }
        //validated
        return true;
    }
}
